const countDown = (time) => {
  var inputTime = +new Date(time);
  var nowTime = +new Date();
  var times = (nowTime - inputTime) / 1000;
  var d = parseInt(times / 60 / 60 / 24);
  d = d < 10 ? "0" + d : d;
  var h = parseInt((times / 60 / 60) % 24);
  h = h < 10 ? "0" + h : h;
  var m = parseInt((times / 60) % 60);
  m = m < 10 ? "0" + m : m;
  var s = parseInt(times % 60);
  s = s < 10 ? "0" + s : s;
  return `相恋：${d}天 ${h}小时${m}分${s}秒`;
};

/*
* before: 上传前的操作
* fileURL: 临时文件路径
* name: 储存文件夹
* successFn: 成功回调
* failFn: 失败回调
*/
const uploadFile = (before, fileURL, name, successFn, failFn) => {
  before();
  wx.cloud.uploadFile({
    cloudPath: name + "/" + name + new Date().getTime() + ".png", // 上传至云端的路径
    filePath: fileURL, // 小程序临时文件路径
    success: (res) => {
      const fileID = res.fileID;
      //获取图片的http路径，准备添加到数据库中
      wx.cloud.getTempFileURL({
        fileList: [fileID],
        success: (res) => {
          const url = res.fileList[0].tempFileURL;
          successFn(url, fileID);
        },
        fail: () => {
          failFn();
        },
      });
    },
    fail: () => {
      failFn();
    },
  });
};

/*
* num: 积分数量
* notice: 温馨提示内容
* navigateBack: 是否返回上个页面
*/
const subscribe = (num, notice, navigateBack) => { //点击用户授权订阅按钮事件
  const that = this;
  wx.getSetting({
    withSubscriptions: true,
    success: res => {
      // console.log(res.subscriptionsSetting.mainSwitch);
      if (res.subscriptionsSetting.mainSwitch) {
        wx.requestSubscribeMessage({
          tmplIds: ['b6PLBh979F4ZkuBXgmuAygGutvj4FGflLP67iW14u1c'],
          success(res) {
            // console.log(res);
            if (res['b6PLBh979F4ZkuBXgmuAygGutvj4FGflLP67iW14u1c'] == 'accept') {
              if (navigateBack) {
                wx.navigateBack(1);
              }
              wx.cloud.callFunction({
                name: 'message',
                data: {
                  type: '心动值',
                  num,
                  notice,
                }
              }).then((res) => { })
            } else {
              //用户没有点击同意订阅
              if (navigateBack) {
                wx.navigateBack(1);
              }
            }
          },
          fail: (err) => { console.log(err) }
        })
      } else {
        if (navigateBack) {
          wx.navigateBack(1);
        }
      }
    }
  })
};

module.exports = {
  countDown,
  uploadFile,
  subscribe
};
